package com.ncmmall.api.apis.mall;


import com.ncmmall.api.apis.service.ChineseToSpell;
import com.ncmmall.api.apis.service.Result;
import com.ncmmall.application.business.member.MemberApplication;
import com.ncmmall.domain.business.goods.brand.GoodsBrand;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author linxs
 *         品牌商品
 */
@RestController
@RequestMapping(value = "/brand")
@Component
public class BrandApi {

    private Logger logger = LoggerFactory.getLogger(BrandApi.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MemberApplication memberApplication;

    @Value("${store.domain}")
    private String storeDomain;

    @RequestMapping(value = "/brandList", method = RequestMethod.GET)
    @ResponseBody
    public Result brandList(HttpServletRequest request) {
        Result result = new Result();
        try {

            List<GoodsBrand> brands = queryChannelService.findAll("select b from GoodsBrand b where b.status = 3 ", GoodsBrand.class);

            Map<String, List<GoodsBrand>> data = Maps.newHashMap();

            for (GoodsBrand brand : brands) {
                brand.setLogo(storeDomain + "/uploads/" + brand.getLogo());

                String brandFirstWord = ChineseToSpell.getFullSpell(brand.getName()).substring(0, 1);

                if (data.containsKey(brandFirstWord)) {
                    List<GoodsBrand> brandsOfCurrent = data.get(brandFirstWord);
                    brandsOfCurrent.add(brand);
                    data.put(brandFirstWord, brandsOfCurrent);
                } else {

                    List<GoodsBrand> brandsOfCurrent = Lists.newArrayList();

                    brandsOfCurrent.add(brand);
                    data.put(brandFirstWord, brandsOfCurrent);
                }
            }

            Map<String, List<GoodsBrand>> finishData = new TreeMap<>(new Comparator<String>() {
                public int compare(String obj1, String obj2) {
                    return obj1.compareTo(obj2);
                }
            });

            finishData.putAll(data);


            return result.ok().inject(finishData);

        } catch (Exception e) {

            logger.error("[分类商品列表获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }


    /**
     * 分类商品列表
     *
     * @param request
     * @param keyword   搜索关键字
     * @param orderType 排序类型
     *                  1、最新
     *                  2、价格
     *                  3、销量
     * @param orderBy   asc 顺序
     *                  desc 逆序
     * @param maxPrice  最高价格
     * @param minPrice  最低价格
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Result list(HttpServletRequest request, @RequestParam long id, @RequestParam(defaultValue = "0") int orderType, String orderBy, @RequestParam(defaultValue = "0") double maxPrice, @RequestParam(defaultValue = "0") double minPrice, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "20") int pageSize) {
        Result result = new Result();
        try {

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);
            Map<String, Object> map = new HashMap<>();

            String hql = "select id, name, defaultPrice, marketPrice, defaultImage from mall_goods where status = 3 and isSupplier = 1 and brand_id = :id ";
            map.put("id", id);

            hql = builderSQL(orderType, orderBy, maxPrice, minPrice, map, hql);

            QueryPage<Map<String, Object>> page = queryChannelService.selectPageMap(hql, pageRequest.setParams(map));
            for (Map<String, Object> goods : page.getResult()) {
                if (goods.get("defaultImage") != null) {
                    goods.put("defaultImage", storeDomain + "/uploads/" + goods.get("defaultImage"));
                }
            }

            return result.ok().inject(page);

        } catch (Exception e) {

            logger.error("[分类商品列表获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    private String builderSQL(@RequestParam(defaultValue = "0") int orderType, String orderBy, @RequestParam(defaultValue = "0") double maxPrice, @RequestParam(defaultValue = "0") double minPrice, Map<String, Object> map, String hql) {

        if (maxPrice > 0) {
            hql += " and defaultPrice <= :maxPrice";
            map.put("maxPrice", maxPrice);
        }

        if (minPrice > 0) {
            hql += " and defaultPrice >= :minPrice";
            map.put("minPrice", minPrice);
        }

        if (orderType > 0 && ("ASC".equals(orderBy.toUpperCase()) || "DESC".equals(orderBy.toUpperCase()))) {
            if (orderType == 1) {
                hql += " order by createTime " + orderBy.toUpperCase();
            } else if (orderType == 2) {
                hql += " order by defaultPrice " + orderBy.toUpperCase();
            } else if (orderType == 3) {
                //todo 按销量排序
                //                    hql += " order by createTime " + orderBy.toUpperCase();
            }
        } else {
            hql += " order by createTime desc";
        }
        return hql;
    }


}
